package com.dayuanit.dy15.ebook.bookshop.service.impl;

import com.dayuanit.dy15.ebook.bookshop.domain.CardDomain;
import com.dayuanit.dy15.ebook.bookshop.dto.CardDTO;
import com.dayuanit.dy15.ebook.bookshop.entity.Card;
import com.dayuanit.dy15.ebook.bookshop.exception.BizException;
import com.dayuanit.dy15.ebook.bookshop.mapper.CardMapper;
import com.dayuanit.dy15.ebook.bookshop.service.CardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class CardServiceImpl implements CardService {

    @Value("${ebook.picture.url}")
    private String pictureUrl;

    @Autowired
    private CardMapper cardMapper;

    @Override
    public void addCard(long commodityId, long userId) {

        //如果商品已经存在 则更新，反之则添加
        //userID和commodityID在数据库总是复合索引，where语句在使用的时候，顺序和索引顺序要保持一致
        //否则，sql语句可能不走索引，速度也自然上不去。
        Card card = cardMapper.getByUserAndCommoId(userId, commodityId);
        if (card != null) {
            cardMapper.updateBuyNum(userId, commodityId);
            return;
        }

        card = new Card();
        card.setBuyNum(1);
        card.setCommodityId(commodityId);
        card.setCreateTime(new Date());
        card.setModifyTime(card.getCreateTime());
        card.setUserId(userId);
        cardMapper.insert(card);
    }

    @Override
    public List<CardDTO> listCards(long usreId) {
        List<CardDomain> cards = cardMapper.listCardByUserId(usreId);
        if (cards.isEmpty()) {
            return Collections.emptyList();
        }

        List<CardDTO> dtos = new ArrayList<>(cards.size());

        for (CardDomain card : cards) {
            CardDTO cardDTO = new CardDTO();
            dtos.add(cardDTO);

            cardDTO.setBuyNum(card.getBuyNum());
            cardDTO.setCommodityId(card.getCommodityId());
            cardDTO.setPictureUrl(pictureUrl + card.getPictureName());
            cardDTO.setPrice(card.getPrice());
            cardDTO.setCardId(card.getCardId());
            cardDTO.setCommodityName(card.getCommodityName());
        }
        return dtos;
    }

    @Override
    public void deleteCard(long userId, long cardId) {
        Card card = cardMapper.selectByPrimaryKey(cardId);
        if (null == card || card.getUserId() != userId) {
            throw new BizException("删除失败");
        }

        cardMapper.updateBuyNum4Del(cardId);
    }
}
